<template>
	<view class="container">
		<!-- 顶部筛选栏 -->
		<view class="filter-bar">
			<!-- <view 
				class="filter-item" 
				:class="{ active: selectedFilter === 'all' }"
				@click="selectFilter('all')"
			>
				<text class="filter-text">全部</text>
			</view> -->
			<view 
				class="filter-item" 
				:class="{ active: selectedFilter === 'pending' }"
				@click="selectFilter('pending')"
			>
				<text class="filter-text">待发货</text>
				<view class="filter-badge" v-if="pendingCount > 0">
					<text class="badge-text">{{ pendingCount }}</text>
				</view>
			</view>
			<!-- <view 
				class="filter-item" 
				:class="{ active: selectedFilter === 'paydebt' }"
				@click="selectFilter('paydebt')"
			>
				<text class="filter-text">欠款补交</text>
				<view class="filter-badge" v-if="paydebtCount > 0">
					<text class="badge-text">{{ paydebtCount }}</text>
				</view>
			</view> -->
			<!-- <view 
				class="filter-item" 
				:class="{ active: selectedFilter === 'payaudit' }"
				@click="selectFilter('payaudit')"
			>
				<text class="filter-text">审核</text>
				<view class="filter-badge" v-if="payauditCount > 0">
					<text class="badge-text">{{ payauditCount }}</text>
				</view>
			</view> -->
			<view 
				class="filter-item" 
				:class="{ active: selectedFilter === 'received' }"
				@click="selectFilter('received')"
			>
				<text class="filter-text">待收货</text>
				<view class="filter-badge" v-if="receivedCount > 0">
					<text class="badge-text">{{ receivedCount }}</text>
				</view>
			</view>
			<view 
				class="filter-item" 
				:class="{ active: selectedFilter === 'topay' }"
				@click="selectFilter('topay')"
			>
				<text class="filter-text">已完成</text>
			</view>
		</view>
		
	<!-- 订单列表 -->
	<view class="order-list">
		<!-- 空状态 -->
		<view class="empty-container" v-if="!loading && orders.length === 0">
			<text class="empty-text">暂无订单</text>
		</view>
		
		<view 
			class="order-card" 
			v-for="order in orders" 
			:key="order.id"
		>
			<!-- 订单时间 -->
			<view class="order-time">
				<text class="time-text">{{ order.time }}</text>
				<text class="order-status">{{ order.status }}</text>
			</view>
			
			<!-- 店铺名和下单人 -->
			<view class="order-info">
				<text class="info-text" v-if="order.storeName">{{ order.storeName }}</text>
				<text class="info-text" v-if="order.userName">{{ order.userName }}</text>
			</view>
			
			<!-- 订单商品 -->
				<view class="order-items" @click="goToOrderDetails(order)">
					<view 
						class="item-preview" 
						v-for="(item, index) in order.items" 
						:key="index"
					>
						<image class="item-image" v-if="item.image" :src="item.image" mode="aspectFill"></image>
						<image class="item-image" style="border:1px solid #f0f0f0;" v-else src="../common/images/noImage.png" mode="aspectFill"></image>
						<text class="item-name">{{ item.name }}</text>
					</view>
				</view>
				
				<!-- 订单总价和数量 -->
				<view class="order-summary">
					<view class="price-info">
						<text class="total-price">总销量：¥ {{ order.totalCostPrice }} </text>
						<text class="total-price">进货价：¥ {{ order.totalPrice }} 
							<!-- <text class="pay-status" v-if="order.payStatus == 0">（计入欠款）</text>
							<text class="pay-status" v-if="order.payStatus == 1 && order.payMethodId == 0">（已支付）</text>
							<text class="pay-status" v-if="order.payStatus == 1 && order.payMethodId == 1">（已补交）</text>
							<text class="pay-status" v-if="order.payStatus == 2">（补交中）</text> -->
						</text>
						<text class="item-count">共{{ order.totalCount }}件</text>
					</view>
					<view class="action-btn-group">
						<!-- 确认收货 -->
						<view class="action-btn" v-if="order.orderStatus == 2 && order.payStatus == 1" @click="updateOrderStatus(order.id,3)">
							<text class="btn-text">确认收货</text>
						</view>
						<!-- 欠款补交 -->
						<view class="action-btn" v-if="order.payStatus == 0 && order.orderStatus == 2" @click="goToPay(order)">
							<text class="btn-text">欠款补交</text>
						</view>	
						<!-- 再来一单 -->
						<view class="action-btn" v-if="order.orderStatus == 3" @click="goToConfirmOrder(order.items)">
							<text class="btn-text">再来一单</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部导航栏 -->
		<view class="bottom-nav">
			<view class="nav-item" @click="goToShoppingMall">
				<text class="nav-icon">
					<image src="../common/images/index1.png" mode="aspectFill"></image>
				</text>
				<text class="nav-label">首页</text>
			</view>
			<view class="nav-item" @click="goToShoppingCart">
				<text class="nav-icon">
					<image src="../common/images/car1.png" mode="aspectFill"></image>
				</text>
				<text class="nav-label">购物车</text>
			</view>
			<view class="nav-item active">
				<text class="nav-icon">
					<image src="../common/images/order2.png" mode="aspectFill"></image>
				</text>
				<text class="nav-label">订单</text>
				<view class="nav-badge" v-if="pendingCount + receivedCount > 0">
					<text class="nav-badge-text">{{ pendingCount + receivedCount }}</text>
				</view>
			</view>
			<view class="nav-item" @click="goToShoppingOrderList">
				<text class="nav-icon">
					<image src="../common/images/order1.png" mode="aspectFill"></image>
				</text>
				<text class="nav-label">交款订单</text>
			</view>
		</view>
		
		<!-- 底部指示器 -->
		<view class="home-indicator"></view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			selectedFilter: 'received',
			orders: [],
			allOrders: [], // 保存所有订单数据
			loading: false,
			pendingCount: 0, // 待审核数量
			receivedCount: 0, // 待收货数量
			paydebtCount: 0, // 欠款补交数量
			payauditCount: 0 // 欠款审核数量
		}
	},
	onLoad() {
		// 页面初始化，不在这里加载数据，统一在 onShow 中加载
	},
	onShow() {
		// 页面显示时加载订单列表（包括首次进入和从其他页面返回）
		this.loadOrderList()
	},
	methods: {
		// 加载订单列表
		loadOrderList() {
			this.loading = true
			uni.showLoading({
				title: '加载中...',
				mask: true
			})
			
			this.$u.api.orderManagement.list().then(res => {
				uni.hideLoading()
				this.loading = false
				
				if (res && res.data) {
					// 保存所有订单
					this.allOrders = res.data.map(item => ({
						id: item.id,
						orderNo: item.orderNo,
						time: item.createDate || '',
						status: item.orderStatusName || '',
						orderStatus: item.orderStatus,
						items: (item.itemList || []).map(product => ({
							id: product.productId,
							name: product.productName || '',
							image: product.productImage || '',
							price: product.productPrice || 0,
							costPrice: product.productCostPrice || 0,
							quantity: product.quantity || 0
						})),
						totalPrice: item.totalAmount || 0,
						totalCostPrice: item.totalCostAmount || 0,
						totalCount: (item.itemList || []).reduce((sum, p) => sum + (p.quantity || 0), 0),
						storeName: item.shopName || '',
						receiverName: item.receiverName || '',
						receiverPhone: item.receiverPhone || '',
						receiverAddress: item.receiverAddress || '',
						receiveDate: item.receiveDate || '',
						remark: item.remark || '',
						payMethod: item.payMethod || '',
						payMethodId: item.payMethodId || 0,
						payStatus: item.payStatus,
						userName: item.userName || ''
					}))
					
				// 计算各状态订单数量
				this.pendingCount = this.allOrders.filter(o => o.orderStatus == 1).length
				this.receivedCount = this.allOrders.filter(o => o.orderStatus == 2 && o.payStatus == 1).length
				this.paydebtCount = this.allOrders.filter(o => o.orderStatus == 2 && o.payStatus == 0).length
				this.payauditCount = this.allOrders.filter(o => o.orderStatus == 2 && o.payStatus == 2).length
					// 根据当前筛选条件过滤订单
					this.filterOrders()
				} else {
					this.allOrders = []
					this.orders = []
				}
			}).catch(err => {
				uni.hideLoading()
				this.loading = false
				console.error('获取订单列表失败:', err)
				uni.showToast({
					title: '获取订单列表失败',
					icon: 'none'
				})
			})
		},
		
	// 根据筛选条件过滤订单
	filterOrders() {
		if (this.selectedFilter === 'all') {
			this.orders = this.allOrders
		} else if (this.selectedFilter === 'pending') {
			// 待发货：orderStatus = 1
			this.orders = this.allOrders.filter(o => o.orderStatus == 1)
		} else if (this.selectedFilter === 'paydebt') {
			// 欠款补交：payStatus = 0
			this.orders = this.allOrders.filter(o => o.orderStatus == 2 && o.payStatus == 0)
		} else if (this.selectedFilter === 'payaudit') {
			// 欠款审核：payStatus = 2
			this.orders = this.allOrders.filter(o => o.orderStatus == 2 && o.payStatus == 2)
		} else if (this.selectedFilter === 'received') {
			// 待收货：orderStatus = 2
			this.orders = this.allOrders.filter(o => o.orderStatus == 2 && o.payStatus == 1)
		} else if (this.selectedFilter === 'topay') {
			// 已完成：orderStatus = 3
			this.orders = this.allOrders.filter(o => o.orderStatus == 3)
		}
	},
		selectFilter(filter) {
			this.selectedFilter = filter
			this.filterOrders()
		},
		goToShoppingMall() {
			uni.navigateTo({
				url: '/pages/inventoryManagement/shoppingMall'
			})
		},
		goToShoppingCart() {
			uni.navigateTo({
				url: '/pages/inventoryManagement/shoppingCart'
			})
		},
		goToShoppingOrderList() {
			uni.navigateTo({
				url: '/pages/inventoryManagement/shoppingOrderList?byShop=1'
			})
		},
		goToConfirmOrder(items) {
			uni.navigateTo({
				url: '/pages/inventoryManagement/confirmOrder?cart=' + JSON.stringify(items)
			})
		},
		goToPay(order) {
			uni.navigateTo({
				url: '/pages/inventoryManagement/payDebt?order=' + JSON.stringify(order)
			})
		},
		updateOrderStatus(id,status) {
			// 确定要收货吗
			uni.showModal({
				title: '提示',
				content: '确定要收货吗',
				success: (res) => {
					if (res.confirm) {
						this.updateOrderStatusToServer(id,status)
					}
				}
			})
		},
		updateOrderStatusToServer(id,status) {
			uni.showLoading({
				title: '操作中...',
				mask: true
			})
			this.$u.api.orderManagement.updateStatus({
				orderNo: id,
				orderStatus: status
			}).then(res => {
				if (res && res.result === 'true') {
					uni.showToast({
						title: '操作成功',
						icon: 'success'
					})
					this.loadOrderList()
				} else {
					uni.hideLoading()
					uni.showToast({
						title: res.message || '操作失败',
						icon: 'none'
					})
				}
			}).catch(err => {
				uni.hideLoading()
				console.error('操作失败:', err)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
			}).finally(() => {
				uni.hideLoading()
			})
		},
		goToOrderDetails(order) {
			uni.navigateTo({
				url: '/pages/inventoryManagement/orderDetails?order=' + JSON.stringify(order)
			})
		}
	},
	onBackPress() {
		// 拦截返回按钮，返回到首页
		uni.reLaunch({
			url: '/pages/sys/home/index4'
		})
		return true
	}
}
</script>

<style scoped>
.container {
	background-color: #ffffff;
	display: flex;
	flex-direction: column;
	padding-bottom: 120px;
}

/* 顶部筛选栏 */
.filter-bar {
	position: fixed;
	top: 40px;
	left: 0;
	right: 0;
	display: flex;
	background-color: #ffffff;
	border-bottom: 1px solid #f0f0f0;
	padding: 0 20px;
	z-index: 999;
}
/* #ifdef APP-PLUS */
.filter-bar {
	top: 0px;
}
/* #endif */
.filter-item {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 15px 0;
	position: relative;
}

.filter-text {
	font-size: 12px;
	color: #333333;
}

.filter-item.active .filter-text {
	color: #333333;
	font-weight: bold;
}

.filter-item.active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 20px;
	height: 2px;
	background-color: #000000;
}

.filter-badge {
	position: absolute;
	top: 4px;
	right: 0px;
	width: 16px;
	height: 16px;
	background-color: #ff4069;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.badge-text {
	font-size: 10px;
	color: #ffffff;
	font-weight: bold;
}

/* 订单列表 */
.order-list {
	flex: 1;
	padding: 20px;
	margin-top: 50px;
}

/* 空状态 */
.empty-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 80px 20px;
}

.empty-text {
	font-size: 14px;
	color: #999999;
	margin-top: 20px;
}

.order-card {
	background-color: #ffffff;
	border-radius: 12px;
	padding: 20px;
	margin-bottom: 15px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.order-status {
	font-size: 14px;
	color: #ff4069;
}

/* 订单时间 */
.order-time {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10px;
}

.time-text {
	font-size: 14px;
	color: #666666;
}

/* 店铺名和下单人 */
.order-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10px;
	flex-wrap: wrap;
}

.info-text {
	font-size: 12px;
	color: #333333;
}

/* 订单商品 */
.order-items {
	max-height: 70px;
	overflow: hidden;
	display: flex;
	flex-wrap: wrap;
	gap: 15px;
	margin-bottom: 15px;
}

.item-preview {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.item-image {
	width: 40px;
	height: 40px;
	border-radius: 8px;
	background-color: #f0f0f0;
	margin-bottom: 5px;
}

.item-name {
	font-size: 10px;
	color: #333333;
}

/* 订单总价和数量 */
.order-summary {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.price-info {
	display: flex;
	flex-direction: column;
}

.total-price {
	font-size: 12px;
	color: #333333;
	font-weight: bold;
	margin-bottom: 2px;
}

.pay-status {
	font-size: 10px;
	line-height: 14px;
	color: #ff4069;
}
.item-count {
	font-size: 10px;
	color: #333333;
}

.action-btn-group {
	display: flex;
	gap: 10px;
}

.action-btn {
	padding: 4px 8px;
	border: 1px solid #333333;
	border-radius: 20px;
}

.btn-text {
	font-size: 12px;
	color: #333333;
}

/* 底部导航栏 */
.bottom-nav {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 60px;
	background-color: #ffffff;
	border-top: 1px solid #f0f0f0;
	display: flex;
	z-index: 100;
}

.nav-item {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	position: relative;
}

.nav-icon {
	font-size: 20px;
	color: #666666;
	display: flex;
	align-items: center;
	justify-content: center;
}

.nav-icon image {
	width: 25px;
	height: 25px;
}

.nav-label {
	font-size: 12px;
	color: #666666;
}

.nav-item.active .nav-icon {
	color: #ff4069;
}

.nav-item.active .nav-label {
	color: #ff4069;
}

.nav-badge {
	position: absolute;
	top: 5px;
	right: 20px;
	width: 16px;
	height: 16px;
	background-color: #ff4069;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.nav-badge-text {
	font-size: 10px;
	color: #ffffff;
	font-weight: bold;
}

/* 底部指示器 */
.home-indicator {
	position: fixed;
	bottom: 10px;
	left: 50%;
	transform: translateX(-50%);
	width: 40px;
	height: 4px;
	background-color: #000000;
	border-radius: 2px;
}
</style>
